package edu.vt.ece4564;

import android.os.Bundle;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

public class DiscoveryActivity extends Activity implements OnClickListener{
    // Debugging
    private static final String TAG = "DeviceDiscoveryActivity";
    private static final boolean D = true;
	
    // Intent request codes
    private static final int REQUEST_ENABLE_BT = 3;
    
	// Create a BroadcastReceiver for ACTION_FOUND
	private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
		@Override
	    public void onReceive(Context context, Intent intent) {
	        String action = intent.getAction();
	        // When discovery finds a device
	        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
	            // Get the BluetoothDevice object from the Intent
	            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                // If it's already paired, skip it, because it's been listed already
                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                    mDevicesArrayAdapter_.add(device.getName() + "\n" + device.getAddress());
                }
                // When discovery is finished, change the Activity title
                } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                    setProgressBarIndeterminateVisibility(false);
                    setTitle(R.string.select_devices);
                    if (mDevicesArrayAdapter_.getCount() == 0) {
                        String noDevices = getResources().getText(R.string.no_devices_found).toString();
                        mDevicesArrayAdapter_.add(noDevices);
                }
                
	        }
	    }
	};
	
	// Member fields
    private ArrayAdapter<String> mDevicesArrayAdapter_ = null;
	private BluetoothAdapter mBluetoothAdapter_ = null;
	
	// Member Buttons
	private Button bluetoothScan_;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        // Setup Window
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        setContentView(R.layout.discovery_activity_layout_list);
        
        // Set result CANCELED in case the user backs out
        setResult(Activity.RESULT_CANCELED);
        
        // Initialize Search Button
        bluetoothScan_ = (Button) findViewById(R.id.scanBluetooth);
        bluetoothScan_.setOnClickListener(this);
        
        // Initialize Array Adapter
        mDevicesArrayAdapter_ = new ArrayAdapter<String>(this, R.layout.device_list);
        
        // Initialize ListView for devices
        ListView devicesListView = (ListView) findViewById(R.id.devices);
        devicesListView.setAdapter(mDevicesArrayAdapter_);
        
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    	registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy
        
		mBluetoothAdapter_ = BluetoothAdapter.getDefaultAdapter();
		if (mBluetoothAdapter_ == null) {
            Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
            finish();
            return;
		}
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();

        // Make sure we're not doing discovery anymore
        if (mBluetoothAdapter_ != null) {
        	mBluetoothAdapter_.cancelDiscovery();
        }

        // Unregister broadcast listeners
        this.unregisterReceiver(mReceiver);
    }
    
    @Override
    public void onStart() {
        super.onStart();
        if(D) Log.e(TAG, "++ ON START ++");

        // If BT is not on, request that it be enabled.
        // setupChat() will then be called during onActivityResult
        if (!mBluetoothAdapter_.isEnabled()) {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
        // Otherwise, setup the chat session
        }
    }

	@Override
	public void onClick(View v) {
		bluetoothScan_.setText(R.string.rescan);
        
		// Indicate scanning in the title
        setProgressBarIndeterminateVisibility(true);
        setTitle(R.string.scanning);

        // If we're already discovering, stop it
        if (mBluetoothAdapter_.isDiscovering()) {
            mBluetoothAdapter_.cancelDiscovery();
        }
        
        mDevicesArrayAdapter_.clear();

        // Request discover from BluetoothAdapter
        mBluetoothAdapter_.startDiscovery();
	}
}
